const dbCloud = require('../dbCloud.js');

const { db_account, db } = dbCloud;

/**
 * 分页查询方法
 */
const queryAccounts = async (userId, skipNum, limitNum) => {
  return db_account.where({
    _openid: userId
  })
  .orderBy('time', 'desc')
  .orderBy('updatedAt', 'desc')
  .skip(skipNum)
  .limit(limitNum).get();
};

/**
 * 根据主键删除支出
 */
const deleteAccountById = async (id) => {
  return db_account.doc(id).remove();
};

/**
 * 根据id获取支出
 */
const queryAccountById = async (id) => {
  return db_account.doc(id).get();
};

/**
 * 查询所有的支出
 */
const queryAllAccounts = async (userId) => {
  const MAX_LIMIT = 100
  const countResult = await db_account.count();
  const total = countResult.total;
  // 计算需分几次取
  const batchTimes = Math.ceil(total / MAX_LIMIT);
  // 承载所有读操作的 promise 的数组
  const tasks = [];
  for (let i = 0; i < batchTimes; i++) {
    const promise = db_account.skip(i * MAX_LIMIT).limit(MAX_LIMIT).where({
      _openid: userId
    }).get();
    tasks.push(promise);
  }
  // 等待所有
  return (await Promise.all(tasks)).reduce((acc, cur) => ({
    data: acc.data.concat(cur.data),
    errMsg: acc.errMsg
  }));
};

/**
 * 获取和
 */
const queryTotalAccount = async () => {
  const $ = db.command.aggregate;
  var result = await db_account
    .aggregate()
    .group({
      _id: null,
      total: $.sum('$accountVal')
    })
    .end();
  return result.list[0];
};



/**
 * 新增账单
 */
const addAccout = async (params) => {
  return await db_account.add({
    data: {
      accountMark: params.accountMark,
      accountType: params.accountType,
      accountName: params.accountName,
      accountVal: Number(params.accountVal),
      time: params.time,
      fileid: params.fileid,
      updatedAt: Date.now(),
      createdAt: Date.now(),
      _openid: params._openid
    }
  });
};

module.exports = {
  queryAccounts,
  queryTotalAccount,
  queryAllAccounts,
  queryAccountById,
  deleteAccountById,
  addAccout
};
